package com.wd.servlet;

import cn.hutool.core.codec.Base64;
import cn.hutool.db.Session;
import com.wd.entity.Log;
import com.wd.entity.User;
import com.wd.service.LogService;
import com.wd.service.UserService;
import com.wd.service.impl.LogServiceImpl;
import com.wd.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * @Author: 悠久的苍穹
 * @Date: 2020/10/13 22:16
 * @Description: ${description}
 * @Version: 1.0
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    UserService userService=new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");
            String name = request.getParameter("userName");
            String password = Base64.encode(request.getParameter("password"));
            HttpSession hs=request.getSession();
            boolean flag=true;
            User user = userService.Login(name, password);
            LogService logService = new LogServiceImpl();

            if(user!=null){
                flag=false;
                if(user.getAccount().equals("admin")){
                    Log log = new Log();
                    log.setId(1);
                    log.setUsername(name);
                    log.setLoginDate(new Date());
                    hs.setAttribute("user",user);
                    hs.setAttribute("tan","1");
                    logService.addLog(log);
                    response.sendRedirect("IndexServlet");
                }else{
                    Log log2 = new Log();
                    log2.setId(1);
                    log2.setUsername(user.getAccount());
                    log2.setLoginDate(new Date());
                    hs.setAttribute("user",user);
                    logService.addLog(log2);
//                    request.getRequestDispatcher("/blog/index.jsp").forward(request,response);
                    response.sendRedirect("/blog/index.jsp");
                }


            }else{
                hs.setAttribute("errorMsg","账号或密码不正确");
                response.sendRedirect("login.jsp");
            }
            if(flag){
                request.getRequestDispatcher("login.jsp");
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
